//
//  LYSmallCardListView.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/23.
//

import UIKit

protocol LYSmallCardListViewDelegate: AnyObject {
    func smallCardList(view: LYSmallCardListView, didSelect receiveer: Receiveer)
}

class LYSmallCardListView: UIView {
    weak var delegate: LYSmallCardListViewDelegate? = nil
    private let tableView = UITableView()
    
    var dataSource: [Receiveer] = [] {
        didSet {
            self.tableView.reloadData()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupTableView()
        backgroundColor = .clear
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupTableView() {
        tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "CustomCell")
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 120
        tableView.backgroundColor = .clear

        addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    func getTableViewListHeight() -> CGFloat {
        return 120 * CGFloat(self.dataSource.count)
    }
}

extension LYSmallCardListView: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableViewCell
        cell.configure(with: dataSource[indexPath.row])
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let receiveer = dataSource[indexPath.row]
        delegate?.smallCardList(view: self, didSelect: receiveer)
    }
}
